<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Foreword extends BaseModel
{
    use HasFactory;

    
    const CREATED_AT='create_time';
    const UPDATED_AT='change_time';

    protected $table = 'foreword';


    /**
     * 关联管理员信息
     */
    public function manageInfo(){
        return $this->belongsTo('App\Models\Manage' , 'manage_id');
    }

    /**
     *  新增前言
     * @param $data 添加的数据
     */
    public function add($data){
        if(empty($data->font_color)){
            $data->font_color = '#000000';
        }
        
        $this->name = $data->name;
        $this->intro = $data->intro;
        $this->intro_en = $data->intro_en;
        $this->img = $data->img;
        $this->subhead = $data->subhead;
        $this->template = $data->template;
        $this->font_color = strpos($data->font_color , '#') !== false ? $data->font_color : '#'.$data->font_color;
        $this->img_thumb = str_replace('.' , '_thumb.' , $data->img);
        $this->roll_speed = $data->roll_speed;
        $this->page_stay_min_time = $data->page_stay_min_time;
        $this->manage_id = $data->manage_id;
        $this->is_del = 1;

        return  $this->save();
    }

    /**
     *  修改前言
     * @param $data 添加的数据
     */
    public function change($data){
        $res = $this->where('is_del' , 1)->find($data['id']);
        if(!$res){
            return false;
        }
        if(empty($data->font_color)){
            $data->font_color = '#000000';
        }

        $res->name = $data->name;
        $res->intro = $data->intro;
        $res->intro_en = $data->intro_en;
        $res->img = $data->img;
        $res->subhead = $data->subhead;
        $res->template = $data->template;
        $res->font_color = strpos($data->font_color , '#') !== false ? $data->font_color : '#'.$data->font_color;
        $res->img_thumb = str_replace('.' , '_thumb.' , $data->img);
        $res->roll_speed = $data->roll_speed;
        $res->page_stay_min_time = $data->page_stay_min_time;
        return  $res->save();
    }


    /**
     * 判断名称是否已经存在
     * @param name 前言名称
     * @param id 前言id   可选，主要是用于修改
     */
    public function forewordNameIsExists($name , $id = null){
        $res = $this->where('name' , $name)->where(function($query) use($id){
                if(!empty($id)){
                    $query->where('id' , '<>' , $id);
                }
        })->where('is_del' , 1)->first();
        return $res;
    }

    /**
     * 判断某个前言是否在展览中
     * @param fore_id 前言id
     */
    public function foreIsExhibition($fore_id){
        $res = Exhibition::where('fore_id' , $fore_id)->where('is_del' , 1)->first();
        return $res;
    }



}
